import axios, { pendingList, cancelToken, removePending } from './cancelRequest'

export const axiosJsonPlaceHolder = axios.create({
  baseURL: 'http://jsonplaceholder.typicode.com/',
  timeout: 30000,
  withCredentials: false
})

axiosJsonPlaceHolder.interceptors.request.use(config => {
  removePending(config) // 在请求发送前执行取消操作
  config.cancelToken = new cancelToken(c => {
    // 标识为请求地址 & 请求方式拼接字符串
    pendingList.push({ u: config.url + '&' + config.method, f: c })
  })

  return config
})

axiosJsonPlaceHolder.interceptors.response.use(
  response => {
    if (response.status === 200) {
      const { success, message, errorMsg, status } = response.data
      if (success === false || status === 'ERROR') {
        return Promise.reject(errorMsg || message || '未知错误')
      } else {
        return response
      }
    }

    return Promise.reject('未知错误')
  },
  error => {
    return Promise.reject(error)
  }
)

import { fetchPosts } from './posts'

export const request = {
  fetchPosts
}
